const { Transaction, User } = require('../models');
const { sequelize } = require('../config/database');
const { Op } = require('sequelize');

// 创建交易（充值/消费）
exports.createTransaction = async (req, res, next) => {
  const t = await sequelize.transaction();
  
  try {
    const { userId, type, amount, description } = req.body;

    // 验证必填字段
    if (!userId || !type || !amount) {
      await t.rollback();
      return res.status(400).json({
        success: false,
        message: '请提供用户ID、交易类型和金额'
      });
    }

    // 验证金额
    if (amount <= 0) {
      await t.rollback();
      return res.status(400).json({
        success: false,
        message: '金额必须大于0'
      });
    }

    // 查找用户
    const user = await User.findByPk(userId, { transaction: t });
    if (!user) {
      await t.rollback();
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    let newBalance;
    if (type === 'recharge') {
      // 充值
      newBalance = parseFloat(user.balance) + parseFloat(amount);
    } else if (type === 'consume') {
      // 消费
      if (parseFloat(user.balance) < parseFloat(amount)) {
        await t.rollback();
        return res.status(400).json({
          success: false,
          message: '余额不足'
        });
      }
      newBalance = parseFloat(user.balance) - parseFloat(amount);
    } else {
      await t.rollback();
      return res.status(400).json({
        success: false,
        message: '无效的交易类型'
      });
    }

    // 更新用户余额
    user.balance = newBalance;
    await user.save({ transaction: t });

    // 创建交易记录
    const transaction = await Transaction.create({
      userId,
      type,
      amount,
      balanceAfter: newBalance,
      description,
      operatorId: req.user.id
    }, { transaction: t });

    await t.commit();

    res.status(201).json({
      success: true,
      message: type === 'recharge' ? '充值成功' : '消费成功',
      data: {
        transaction,
        newBalance
      }
    });
  } catch (error) {
    await t.rollback();
    next(error);
  }
};

// 获取交易记录列表
exports.getTransactions = async (req, res, next) => {
  try {
    const { page = 1, limit = 10, type, userId } = req.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (type) where.type = type;
    if (userId) where.userId = userId;

    const { count, rows: transactions } = await Transaction.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        },
        {
          model: User,
          as: 'operator',
          attributes: ['id', 'name']
        }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        transactions,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取单条交易记录
exports.getTransactionById = async (req, res, next) => {
  try {
    const { id } = req.params;

    const transaction = await Transaction.findByPk(id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        },
        {
          model: User,
          as: 'operator',
          attributes: ['id', 'name']
        }
      ]
    });

    if (!transaction) {
      return res.status(404).json({
        success: false,
        message: '交易记录不存在'
      });
    }

    res.json({
      success: true,
      data: transaction
    });
  } catch (error) {
    next(error);
  }
};

// 获取用户交易记录
exports.getUserTransactions = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 10, type } = req.query;
    const offset = (page - 1) * limit;

    const where = { userId };
    if (type) where.type = type;

    const { count, rows: transactions } = await Transaction.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        transactions,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};
